/*
 * Copyright (c) 2013, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package pyip.lib.mixtool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author yepeng
 * @date 2015年6月4日
 */
public class ImageDownloader {

    private String subffix = ".jpg";
    private int connectTimeout = 6000;
    private int readTimeout = 10000;

    public static void main(String[] args) {
        System.out.println("start ...");
        ImageDownloader downloader = new ImageDownloader();
        // String imgUrl = "http://khcx.gdpost.com.cn/verifyCodeServlet?nowtime=1433403125555";
        String imgUrl = "http://khcx.gdpost.com.cn/verifyCodeServlet?nowtime=";
        String directory = "C://Users//admin//Downloads//ocr-test//dgpost//img";
        int i = 0;
        for (; i < 100; i++) {
            try {
                String imgName = downloader.download(imgUrl + System.currentTimeMillis(), new File(directory), null);
                System.out.println("save img " + imgName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("successful download " + i + " images");
        System.out.println("end ...");
    }

    public ImageDownloader() {
    }

    /**
     * @param imgUrl
     * @param directory
     * @param fileName 如果为空则使用时间戳
     * @throws IOException
     */
    public String download(String imgUrl, File directory, String fileName) throws IOException {
        if (fileName == null || fileName.trim().length() == 0) {
            fileName = String.valueOf(System.currentTimeMillis()) + subffix;
        }
        URL _url = new URL(imgUrl);
        InputStream in = null;
        OutputStream out = null;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) _url.openConnection();
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            in = connection.getInputStream();
            out = new FileOutputStream(new File(directory, fileName));
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            return fileName;
        } catch (IOException e) {
            File file = new File(directory, fileName);
            if (file.exists()) {
                boolean success = file.delete();
                if (!success) {
                    System.out.println("下载出错时删除图片 " + fileName + " 失败");
                }
            }
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
